<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="课程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="启用状态" prop="status">
        <el-select
          v-model="queryParams.status"
          class="!w-240px"
          clearable
          placeholder="请选择启用状态"
        >
          <el-option :value="1" label="启用" />
          <el-option :value="0" label="停用" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="primary" plain @click="handleAdd">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column align="center" label="封面" prop="cover">
        <template #default="scope">
          <el-image
            :preview-src-list="[scope.row.cover]"
            :src="scope.row.cover"
            fit="cover"
            style="width: 80px; height: 50px; border-radius: 4px"
          >
            <template #error>
              <div class="image-slot">
                <el-icon><Picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column align="center" label="课程名称" prop="name" />
      <el-table-column align="center" label="课程分类" prop="courseTypeName" />
      <el-table-column align="center" label="创建者" prop="creator" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180px"
      />
      <el-table-column align="center" label="启用状态" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            :loading="scope.row.statusLoading"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button link type="primary" @click="openForm('update', scope.row.id)">
            编辑
          </el-button>
          <el-button link type="danger" @click="handleDelete(scope.row.id)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 新增弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="800px"
    append-to-body
    destroy-on-close
  >
    <ManageForm ref="formRef" @success="handleSuccess" />
  </el-dialog>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ManageApi, ManageVO } from '@/api/lession/manage'
import ManageForm from './ManageForm.vue'
import { useRouter } from 'vue-router'
import { watch } from 'vue'
import { useCentreStore } from '@/store/modules/lession/centre'
import { Picture } from '@element-plus/icons-vue'

/** 课程管理 列表 */
defineOptions({ name: 'LessionCentre' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const centreStore = useCentreStore()

const loading = ref(true) // 列表的加载中
const list = ref<ManageVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  teacher: undefined,
  catalog: undefined,
  courseType: undefined,
  courseTypeName: undefined,
  cover: undefined,
  status: 1 // 默认启用状态
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 弹窗相关变量
const dialogVisible = ref(false)
const dialogTitle = ref('')

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ManageApi.getManagePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 处理新增按钮点击 */
const handleAdd = () => {
  router.push('/lession/centre/form')
}

/** 处理编辑按钮点击 */
const openForm = (type: string, id?: number) => {
  router.push({
    path: '/lession/centre/form',
    query: {
      type,
      id
    }
  })
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ManageApi.deleteManage(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ManageApi.exportManage(queryParams)
    download.excel(data, '课程管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 表单提交成功的回调 */
const handleSuccess = () => {
  dialogVisible.value = false
  getList()
}

/** 初始化 **/
onMounted(() => {
  console.log(6666)
  getList()
})

// 监听 store 中的刷新标记
watch(
  () => centreStore.needRefresh,
  (newVal) => {
    if (newVal) {
      console.log(111)
      getList()
      centreStore.setNeedRefresh(false)
    }
  },
  { immediate: true }
)

/** 处理状态切换 */
const handleStatusChange = async (row: ManageVO) => {
  // 调用更新状态的 API
  await ManageApi.updateStatus({
    id: row.id,
    status: row.status
  })
  // 提示成功
  message.success(row.status === 1 ? '启用成功' : '停用成功')
  // 刷新列表
  // await getList()
}
</script>

<style scoped>
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}
</style>
